package com.woniuxy.yoga.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.yoga.business.client.CoachClient;
import com.woniuxy.yoga.business.client.OrderClient;
import com.woniuxy.yoga.business.client.ProductClient;
import com.woniuxy.yoga.business.dao.mapper.BusinessAccountMapper;
import com.woniuxy.yoga.business.dao.mapper.BusinessStoreMapper;
import com.woniuxy.yoga.business.dao.model.BusinessAccount;
import com.woniuxy.yoga.business.dao.model.BusinessStore;
import com.woniuxy.yoga.business.dao.model.StoreLoginLog;
import com.woniuxy.yoga.business.model.dto.businessaccount.BusinessAccountDTO;
import com.woniuxy.yoga.business.model.dto.businessaccount.BusinessAccountLoginDTO;
import com.woniuxy.yoga.business.model.dto.businessaccount.BusinessAccountSelDTO;
import com.woniuxy.yoga.business.model.dto.businessaccount.BusinessLoginPhoneDTO;
import com.woniuxy.yoga.business.model.dto.orderinfo.OrderInfoDto;
import com.woniuxy.yoga.business.model.exception.BusinessException;
import com.woniuxy.yoga.business.model.exception.BusinessExceptionCode;
import com.woniuxy.yoga.business.model.param.businessaccount.*;
import com.woniuxy.yoga.business.service.BusinessAccountService;
import com.woniuxy.yoga.commons.core.model.PageInfo;
import com.woniuxy.yoga.commons.core.model.Result;
import com.woniuxy.yoga.commons.core.statedata.BusinessState;
import com.woniuxy.yoga.commons.core.statedata.OrderState;
import com.woniuxy.yoga.commons.core.statedata.UserState;
import com.woniuxy.yoga.commons.idcard.model.ResponseEntity;
import com.woniuxy.yoga.commons.idcard.util.AliCheckIdCard;
import com.woniuxy.yoga.commons.oss.util.OSSUtil;
import com.woniuxy.yoga.commons.redis.util.RedisUtil;
import com.woniuxy.yoga.commons.redis.util.rediskeyutil.BusinessRedisKeyUtil;
import com.woniuxy.yoga.commons.web.util.PersonIdCardUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.omg.CORBA.UserException;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 商家账号表 服务实现类
 * </p>
 *
 * @author 韦用文,刘存益,郎腾霄
 * @since 2023年11月30日
 */
@Service
public class BusinessAccountServiceImpl extends ServiceImpl<BusinessAccountMapper, BusinessAccount> implements BusinessAccountService {


    @Autowired
    private BusinessAccountMapper businessAccountMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private AliCheckIdCard aliCheckIdCard;

    @Autowired
    private OSSUtil ossUtil;
    @Autowired
    private BusinessStoreMapper businessStoreMapper;
    @Autowired
    private OrderClient orderClient;

    /**
     * 商家发送注册验证码
     * @param param
     */
    @Override
    public void sendRegisterCode(BusinessRegisterPhoneParam param) throws Exception {
        //查询该号码是否已被商家注册
        QueryWrapper<BusinessAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_phone",param.getAccountPhone());
        BusinessAccount businessAccount = businessAccountMapper.selectOne(queryWrapper);
        //若该号码已被注册且状态是未注销状态则抛异常
        if (businessAccount!=null&&businessAccount.getAccountState()!= BusinessState.BUSINESS_ACCOUNT_STATE_DELETE) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_PHONE_REGISTED);
        }
        //生成商家一分钟内是否发送过注册短信KEY
        String codeMinuteKey = BusinessRedisKeyUtil.businessRegisterCodeMinute(param.getAccountPhone());
        //生成商家注册短信验证码KEY
        String codeKey = BusinessRedisKeyUtil.businessRegisterCodeKey(param.getAccountPhone());
        //生成记录商家一小时内发送短信的总次数的KEY
        String sendNumbersKey = BusinessRedisKeyUtil.businessSendNumbers(param.getAccountPhone());
        //发送验证码操作
        send(codeMinuteKey,codeKey,sendNumbersKey,param.getAccountPhone());
    }

    /**
     * 商家注册账号返回账号ID
     * @param param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer businessRegister(BusinessRegisterParam param) throws Exception {
        //判断身份证信息是否符合
        //调用实名认证接口
        ResponseEntity response = aliCheckIdCard.checkIdCard(param.getAccountRealname(), param.getAccountIdcard());
        //判断认证是否成功
        //认证失败
        if ((!"10000".equals(response.getCode())) || response.getData().getResult()!=1){
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_AUTHENTICATION_FAIL);
        }
        //判断验证码
        String code = redisUtil.get(BusinessRedisKeyUtil.businessRegisterCodeKey(param.getAccountPhone()));
        if (code==null||!code.equals(param.getCode()))throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_CAPTCHA_ERROR);
        //加锁
        //对账号名、手机号、身份证加锁
        RLock nameLock = redissonClient.getFairLock(BusinessRedisKeyUtil.getLockBusinessNameKey(param.getAccountName()));
        RLock phoneLock = redissonClient.getFairLock(BusinessRedisKeyUtil.getLockBusinessPhoneKey(param.getAccountPhone()));
        RLock idcardLock = redissonClient.getFairLock(BusinessRedisKeyUtil.getLockBusinessIdcardKey(param.getAccountIdcard()));
        RLock lock = redissonClient.getMultiLock(nameLock, phoneLock,idcardLock);
        try {
            if (lock.tryLock(10, TimeUnit.SECONDS)) {
                //判断账号名、手机号、身份证是否重复
                LambdaQueryWrapper<BusinessAccount> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(BusinessAccount::getAccountName,param.getAccountName()).or()
                        .eq(BusinessAccount::getAccountPhone,param.getAccountPhone()).or()
                        .eq(BusinessAccount::getAccountIdcard,param.getAccountIdcard());
                queryWrapper.ne(BusinessAccount::getAccountState, BusinessState.BUSINESS_ACCOUNT_STATE_DELETE);
                List<BusinessAccount> businessAccounts = businessAccountMapper.selectList(queryWrapper);
                if (businessAccounts!=null&&businessAccounts.size()>0) {
                    for (BusinessAccount businessAccount : businessAccounts) {
                        if (businessAccount.getAccountName().equals(param.getAccountName())) {
                            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNTNAME_REGISTED);
                        }else if (businessAccount.getAccountPhone().equals(param.getAccountPhone())){
                            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_PHONE_REGISTED);
                        }else {
                            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_IDCARD_REGISTED);
                        }
                    }
                }
                //通过雪花算法获取昵称
                String nickId = new Snowflake(1, 1).nextIdStr().substring(0,8);
                param.setAccountNickname("商家"+nickId);
                //将传入的信息赋给即将插入的对象上
                BusinessAccount businessAccount = BeanUtil.toBean(param, BusinessAccount.class);
                //设置剩余属性的值
                businessAccount.setAccountRegisterTime(DateUtil.format(new Date(System.currentTimeMillis()), "yyyy-MM-dd HH:mm:ss"));
                businessAccount.setAccountState(BusinessState.BUSINESS_ACCOUNT_STATE_NORMAL);
                businessAccount.setAccountHeader("https://liucunyi.oss-cn-chengdu.aliyuncs.com/266a6f677aaf4598a258947acb404d22.webp");
                businessAccountMapper.addAccount(businessAccount);
                return businessAccount.getAccountId();
            }else {
                throw new Exception("服务器繁忙");
            }
        } finally {
            //释放锁
            lock.unlock();
        }
    }

    /**
     * 商家通过账号密码登录
     * @param param
     * @return
     */
    @Override
    public BusinessAccountLoginDTO businessLoginByName(BusinessAccountLoginParam param) throws UnknownHostException {
        //判断商家账号是否存在
        LambdaQueryWrapper<BusinessAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusinessAccount::getAccountName,param.getAccountName());
        BusinessAccount businessAccount = businessAccountMapper.selectOne(queryWrapper);
        if (businessAccount==null) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_NOTEXITS);
        }
        //判断商家账号状态是否正常
        if (businessAccount.getAccountState()!= BusinessState.BUSINESS_ACCOUNT_STATE_NORMAL) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_STATEERROR);
        }
        //判断账号密码是否正确
        if (!param.getAccountPassword().equals(businessAccount.getAccountPassword())) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_PASS_ERROR);
        }
        //生成商家登录日志
        StoreLoginLog storeLoginLog = BeanUtil.toBean(businessAccount, StoreLoginLog.class);
        String[] split = InetAddress.getLocalHost().toString().split("/");
        storeLoginLog.setLoginAddress(split[1]);
        String loginTime = DateUtil.format(new Date(System.currentTimeMillis()), "yyyy-MM-dd HH:mm:ss");
        storeLoginLog.setLoginTime(loginTime);
        storeLoginLog.setLogRemarks("商家"+businessAccount.getAccountRealname()+"在"+loginTime+"通过账号密码登录");
        //在消息队列中异步执行
        rabbitTemplate.convertAndSend("create-businessLoginLog",storeLoginLog);
        //返回账号信息给前端CreateAdminLogConsumer
        BusinessAccountLoginDTO dto = BeanUtil.toBean(businessAccount, BusinessAccountLoginDTO.class);
        return dto;
    }

    /**
     * 商家发送登录验证码
     * @param param
     */
    @Override
    public void sendLoginCode(BusinessLoginSendParam param) throws Exception {
        //查询该号码是否被注册
        LambdaQueryWrapper<BusinessAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusinessAccount::getAccountPhone,param.getAccountPhone());
        BusinessAccount businessAccount = businessAccountMapper.selectOne(queryWrapper);
        if (businessAccount==null) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_NOTEXITS);
        }
        //账号状态是否正常
        if (businessAccount.getAccountState()!= BusinessState.BUSINESS_ACCOUNT_STATE_NORMAL) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_STATEERROR);
        }
        //生成商家一分钟内是否发送过注册短信KEY
        String codeMinuteKey = BusinessRedisKeyUtil.businessLoginCodeMinute(param.getAccountPhone());
        //生成商家注册短信验证码KEY
        String codeKey = BusinessRedisKeyUtil.businessLoginCodeKey(param.getAccountPhone());
        //生成记录商家一小时内发送短信的总次数的KEY
        String sendNumbersKey = BusinessRedisKeyUtil.businessSendLoginNumbers(param.getAccountPhone());
        //发送验证码操作
        send(codeMinuteKey,codeKey,sendNumbersKey,param.getAccountPhone());
    }

    /**
     * 商家通过手机验证码登录
     * @param param
     * @return
     */
    @Override
    public BusinessLoginPhoneDTO businessLoginByPhone(BusinessLoginPhoneParam param) throws UnknownHostException {
        //判断验证码是否存在或过期
        String codeKey = BusinessRedisKeyUtil.businessLoginCodeKey(param.getAccountPhone());
        String code = redisUtil.get(codeKey);
        if (code==null) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_CAPTCHA_OUTDATE);
        }
        //验证码是否错误
        if (!code.equals(param.getCode())) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_CAPTCHA_ERROR);
        }
        //查询该号码是否被注册
        LambdaQueryWrapper<BusinessAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusinessAccount::getAccountPhone,param.getAccountPhone());
        BusinessAccount businessAccount = businessAccountMapper.selectOne(queryWrapper);
        if (businessAccount==null) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_NOTEXITS);
        }
        //账号状态是否正常
        if (businessAccount.getAccountState()!= BusinessState.BUSINESS_ACCOUNT_STATE_NORMAL) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_STATEERROR);
        }
        //生成商家登录日志
        StoreLoginLog storeLoginLog = BeanUtil.toBean(businessAccount, StoreLoginLog.class);
        String[] split = InetAddress.getLocalHost().toString().split("/");
        storeLoginLog.setLoginAddress(split[1]);
        String loginTime = DateUtil.format(new Date(System.currentTimeMillis()), "yyyy-MM-dd HH:mm:ss");
        storeLoginLog.setLoginTime(loginTime);
        storeLoginLog.setLogRemarks("商家"+businessAccount.getAccountRealname()+"在"+loginTime+"通过手机验证码登录");
        //在消息队列中异步执行
        rabbitTemplate.convertAndSend("create-businessLoginLog",storeLoginLog);
        BusinessLoginPhoneDTO dto = BeanUtil.toBean(businessAccount, BusinessLoginPhoneDTO.class);
        return dto;
    }

    /**
     * 商家修改账号头像操作
     * @param param
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateHeader(UpdateHeaderParam param) throws Exception {
        //查询账号是否存在
        BusinessAccount businessAccount = businessAccountMapper.selectById(param.getAccountId());
        if (businessAccount==null) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_NOTEXITS);
        }
        //账号状态是否正常
        if (businessAccount.getAccountState()!= BusinessState.BUSINESS_ACCOUNT_STATE_NORMAL) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_STATEERROR);
        }
        //上传图片
        MultipartFile image = param.getAccountHeader();
        if (image ==null) throw new Exception("传入图片不能为空");
        //获取上传图片的文件名
        String filename = image.getOriginalFilename();
        //获取图片的类型
        String name = filename.substring(filename.lastIndexOf(".")+1);
        //调用API上传
        String imagePath = ossUtil.uploadFile(image.getInputStream(),name);
        //删除原图片
        String path = FileNameUtil.getName(businessAccount.getAccountHeader());
        ossUtil.deleteFile(path,"liucunyi");
        //修改数据库中的路径
        businessAccount.setAccountHeader(imagePath);
        businessAccountMapper.updateById(businessAccount);
    }

    /**
     * 商家修改账号密码操作
     * @param param
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void changePassword(ChangePasswordParam param) {
        //新密码与原密码是否相同
        if (param.getNewPassword().equals(param.getOldPassword())) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_MODIFY_PASS_REPEAT);
        }
        //查询账号是否存在
        BusinessAccount businessAccount = businessAccountMapper.selectById(param.getAccountId());
        if (businessAccount==null) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_NOTEXITS);
        }
        //账号状态是否正常
        if (businessAccount.getAccountState()!= BusinessState.BUSINESS_ACCOUNT_STATE_NORMAL) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_STATEERROR);
        }
        //原密码是否正确
        if (!param.getOldPassword().equals(businessAccount.getAccountPassword())) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_PASS_ERROR);
        }
        //修改数据库中密码
        businessAccount.setAccountPassword(param.getNewPassword());
        businessAccountMapper.updateById(businessAccount);
    }

    /**
     * 商家修改密码前验证操作
     * @param param
     */
    @Override
    public void checkPassword(CheckPasswordParam param) {
        //查询账号是否存在
        BusinessAccount businessAccount = businessAccountMapper.selectById(param.getAccountId());
        if (businessAccount==null) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_NOTEXITS);
        }
        //账号状态是否正常
        if (businessAccount.getAccountState()!= BusinessState.BUSINESS_ACCOUNT_STATE_NORMAL) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_STATEERROR);
        }
        //验证密码是否正确
        if (!param.getAccountPassword().equals(businessAccount.getAccountPassword())) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_PASS_ERROR);
        }
    }

    /**
     * 商家修改昵称操作
     * @param param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeNickName(ChangeNickNameParam param) {
        //查询账号是否存在
        BusinessAccount businessAccount = businessAccountMapper.selectById(param.getAccountId());
        if (businessAccount==null) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_NOTEXITS);
        }
        //查询新昵称与旧昵称是否相同
        if (param.getAccountNickname().equals(businessAccount.getAccountNickname())) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_MODIFY_NICKNAME_REPEAT);
        }
        //账号状态是否正常
        if (businessAccount.getAccountState()!= BusinessState.BUSINESS_ACCOUNT_STATE_NORMAL) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_STATEERROR);
        }
        //修改数据库中昵称
        businessAccount.setAccountNickname(param.getAccountNickname());
        businessAccountMapper.updateById(businessAccount);
    }

    /**
     * 查询商家账号信息操作
     * @param businessId
     * @return
     */
    @Override
    public BusinessAccountSelDTO selBusiness(Integer businessId) {
        //查询账号是否存在
        BusinessAccount businessAccount = businessAccountMapper.selectById(businessId);
        if (businessAccount==null) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_NOTEXITS);
        }
        //调用工具类中获得出生日期 年龄 性别的方法
        Map<String, String> birAgeSex = PersonIdCardUtil.getBirAgeSex(businessAccount.getAccountIdcard());
        String ageStr = birAgeSex.get("age");
        //性别格式：F-女，M-男
        String sexCode = birAgeSex.get("sexCode");
        String gender = "";
        if (sexCode.equals("F")) {
            gender="女";
        }else {
            gender="男";
        }
        Integer age = Integer.parseInt(ageStr);
        BusinessAccountSelDTO dto = BeanUtil.toBean(businessAccount, BusinessAccountSelDTO.class);
        dto.setAge(age);
        dto.setSex(gender);
        return dto;
    }

    /**
     * 商家注销账号操作
     * @param businessId
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void businessDelete(Integer businessId) {
        //是否已注销
        BusinessAccount businessAccount = businessAccountMapper.selectById(businessId);
        if (businessAccount==null) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_NOTEXITS);
        }
        if (businessAccount.getAccountState()== BusinessState.BUSINESS_ACCOUNT_STATE_DELETE) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_DELETED);
        }
        //门店是否已注销
        LambdaQueryWrapper<BusinessStore> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusinessStore::getAccountId,businessId).notIn(BusinessStore::getStoreState,BusinessState.STORE_STATE_DELETE);
        BusinessStore businessStore = businessStoreMapper.selectOne(queryWrapper);
        if (businessStore!=null) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_STORE_NOTDEL);
        }
        //是否存在未完成的业务
        Result<List<OrderInfoDto>> orderResult = orderClient.listOrdersByStoreId(businessStore.getStoreId());
        if (orderResult.getCode()!=200) {
            throw new BusinessException(orderResult.getCode(),orderResult.getMessage());
        }
        List<OrderInfoDto> orderInfoDtos = orderResult.getData();
        for (OrderInfoDto orderInfoDto : orderInfoDtos) {
            if (orderInfoDto.getOrderState()!= OrderState.ORDER_STATE_CANCEL&&orderInfoDto.getOrderState()!=OrderState.ORDER_STATE_DONE) {
                throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ORDER_NOTCOMPLETED);
            }
        }
        //注销账号
        businessAccount.setAccountState(BusinessState.BUSINESS_ACCOUNT_STATE_DELETE);
        businessAccountMapper.updateById(businessAccount);
    }

    /**
     * 平台分页查询商家信息
     * @return
     */
    @Override
    public PageInfo selectPageBusiness(SelectPageBusinessParam param) {
        LambdaQueryWrapper<BusinessAccount> queryWrapper = new LambdaQueryWrapper<>();
        //若传入所属人条件则根据所属人模糊查询
        if (param.getAccountRealname()!=null&&(!param.getAccountRealname().equals(""))) {
            queryWrapper.like(BusinessAccount::getAccountRealname,param.getAccountRealname());
        }
        //除掉已删除的账号
        queryWrapper.notIn(BusinessAccount::getAccountState,BusinessState.BUSINESS_ACCOUNT_STATE_DELETE);
        //开始分页
        Page<BusinessAccount> page = new Page<>(param.getCurrent()==null?1:param.getCurrent(),param.getSize()==null?5:param.getSize());
        businessAccountMapper.selectPage(page,queryWrapper);
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setPages(page.getPages());
        pageInfo.setRecords(BeanUtil.copyToList(page.getRecords(),BusinessAccountDTO.class));
        return pageInfo;
    }

    /**
     * 发送验证码操作
     * @param codeMinuteKey
     * @param codeKey
     * @param sendNumbersKey
     * @param accountPhone
     * @throws Exception
     */
    public void send(String codeMinuteKey, String codeKey, String sendNumbersKey, String accountPhone) throws Exception {
        //若在一分钟内再次发送验证码则抛异常
        if (redisUtil.hasKey(codeMinuteKey)) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_REPEAT_SEND_ONEMINUTE);
        }
        //若在一小时内发送五次以上则抛异常
        String numberString = redisUtil.get(sendNumbersKey);
        if (numberString != null) {
            if (Integer.parseInt(numberString) == 5) {
                throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_FIVE_SEND_ONHOUR);
            }
        }
        //将手机号码保存到businessRegister.sendCode这个队列中
        Map<String, Object> message = new HashMap<>();
        message.put("accountPhone",accountPhone);
        message.put("codeMinuteKey",codeMinuteKey);
        message.put("codeKey",codeKey);
        message.put("sendNumbersKey",sendNumbersKey);
        //将发送验证码操作存入消息队列中 异步进行
        rabbitTemplate.convertAndSend("businessRegister.sendCode",message);
    }
}
